package com.sanno.user.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sanno.user.util.JWTutil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT拦截器
 */
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获得token
        String token = request.getHeader("token");

        Map<String, Object> map = new HashMap<>();
        try {
            JWTutil.verify(token);
            System.out.println("验签通过，放行");
            //如果验签通过，放行访问接口
            return true;
        } catch(TokenExpiredException e){
            map.put("msg", "Token已过期！！！");
            map.put("state", false);
        } catch(SignatureVerificationException e){
            map.put("msg", "签名错误！！！");
            map.put("state", false);
        } catch(AlgorithmMismatchException e){
            map.put("msg", "加密算法不匹配！！！");
            map.put("state", false);
        } catch(Exception e){
            map.put("msg", "无效token！！！");
            map.put("state", false);
        }
        //如果异常，则将异常信息转换成JSON格式响应到前端
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(map);
        //设置响应类型为json，编码为utf-8
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}